<template>
  <div class="editor">
    <iframe :id="editorId" ref="editor"></iframe>
  </div>
</template>

<script>
  export default {
    name: 'DocumentEditor',
    data() {
      return {
        editorId: 'myEditor'
      }
    },
    mounted() {
      const config = {
        document: {
          info: { owner: 'Me', favorite: true, uploaded: 'Fri Jul 07 2023' },
          permissions: {
            comment: true,
            copy: true,
            download: true,
            edit: true,
            print: true,
            fillForms: true,
            modifyFilter: true,
            modifyContentControl: true,
            review: true,
            chat: true,
            reviewGroups: ['', 'group-2'],
            commentGroups: { edit: ['group-2', ''], remove: ['group-2'] },
            userInfoGroups: ['group-2', ''],
            protect: true
          },
          fileType: 'docx',
          key: '-1414147398',
          urlUser:
            'http://192.168.0.200:4000/download?fileName=%E6%96%87%E5%AD%97%E6%96%87%E7%A8%BF1.docx&userAddressD%3A%5CGitRepository%5Cdocument-server-integration%5Cweb%5Cdocumentserver-example%5Cjava-spring%5Cdocuments%5C192.168.0.128%5C',
          title: '文字文稿1.docx',
          url: 'http://192.168.0.200:4000/download?fileName=%E6%96%87%E5%AD%97%E6%96%87%E7%A8%BF1.docx&userAddress=D%3A%5CGitRepository%5Cdocument-server-integration%5Cweb%5Cdocumentserver-example%5Cjava-spring%5Cdocuments%5C192.168.0.128%5C',
          directUrl: '',
          referenceData: {
            instanceId: 'http://192.168.0.200:4000',
            fileKey: '{"userAddress":"192.168.0.128","fileName":"文字文稿1.docx"}'
          }
        },
        documentType: 'word',
        editorConfig: {
          actionLink: {},
          callbackUrl:
            'http://192.168.0.200:4000/track?fileName=%E6%96%87%E5%AD%97%E6%96%87%E7%A8%BF1.docx&userAddress=D%3A%5CGitRepository%5Cdocument-server-integration%5Cweb%5Cdocumentserver-example%5Cjava-spring%5Cdocuments%5C192.168.0.128%5C',
          coEditing: {},
          createUrl: 'http://192.168.0.200:4000/create?fileExt=docx&sample=false',
          customization: {
            logo: { image: '', imageEmbedded: '', url: 'https://www.onlyoffice.com' },
            goback: { url: 'http://192.168.0.200:4000/' },
            autosave: true,
            comments: true,
            compactHeader: false,
            compactToolbar: false,
            compatibleFeatures: false,
            forcesave: false,
            help: false,
            hideRightMenu: true,
            hideRulers: true,
            submitForm: false,
            about: false,
            feedback: false
          },
          embedded: { embedUrl: null, saveUrl: null, shareUrl: null, toolbarDocked: null },
          lang: 'zh',
          mode: 'edit',
          user: { id: '2', name: 'Mark Pottato', group: 'group-2' },
          templates: [
            { image: '', title: 'Blank', url: 'http://192.168.0.200:4000/create?fileExt=docx&sample=false' },
            {
              image: 'http://192.168.0.200:4000/css/img/file_docx.svg',
              title: 'With sample content',
              url: 'http://192.168.0.200:4000/create?fileExt=docx&sample=true'
            }
          ]
        },
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlZGl0b3JDb25maWciOnsiY2FsbGJhY2tVcmwiOiJodHRwOi8vMTkyLjE2OC4wLjIwMDo0MDAwL3RyYWNrP2ZpbGVOYW1lPSVFNiU5NiU4NyVFNSVBRCU5NyVFNiU5NiU4NyVFNyVBOCVCRjEuZG9jeCZ1c2VyQWRkcmVzcz1EJTNBJTVDR2l0UmVwb3NpdG9yeSU1Q2RvY3VtZW50LXNlcnZlci1pbnRlZ3JhdGlvbiU1Q3dlYiU1Q2RvY3VtZW50c2VydmVyLWV4YW1wbGUlNUNqYXZhLXNwcmluZyU1Q2RvY3VtZW50cyU1QzE5Mi4xNjguMC4xMjglNUMiLCJjcmVhdGVVcmwiOiJodHRwOi8vMTkyLjE2OC4wLjIwMDo0MDAwL2NyZWF0ZT9maWxlRXh0PWRvY3gmc2FtcGxlPWZhbHNlIiwiY3VzdG9taXphdGlvbiI6eyJsb2dvIjp7ImltYWdlIjoiIiwiaW1hZ2VFbWJlZGRlZCI6IiIsInVybCI6Imh0dHBzOi8vd3d3Lm9ubHlvZmZpY2UuY29tIn0sImdvYmFjayI6eyJ1cmwiOiJodHRwOi8vMTkyLjE2OC4wLjIwMDo0MDAwLyJ9LCJhdXRvc2F2ZSI6dHJ1ZSwiY29tbWVudHMiOnR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ly8xOTIuMTY4LjAuMjAwOjQwMDAiLCJmaWxlS2V5Ijoie1widXNlckFkZHJlc3NcIjpcIjE5Mi4xNjguMC4xMjhcIixcImZpbGVOYW1lXCI6XCLmloflrZfmlofnqL8xLmRvY3hcIn0ifX0sInR5cGUiOiJkZXNrdG9wIn0.T_O70VkbuKlgUDJ_CVXpLToTU1NRcBhxyWl6IyiNXWo',
        type: 'desktop'
      }
      let docEditor = {}

      const innerAlert = (message, inEditor) => {
        if (console && console.log) {
          console.log(message)
        }
        if (inEditor && docEditor) {
          docEditor.showMessage(message)
        }
      }

      // the application is loaded into the browser
      const onAppReady = () => {
        innerAlert('Document editor ready')
      }

      // the document is modified
      const onDocumentStateChange = event => {
        console.log(event)
      }

      // the user is trying to switch the document from the viewing into the editing mode
      const onRequestEditRights = () => {
        this.$refs.editor.src = this.$refs.editor.src.replace(/&?action=view/i, '')
      }

      // an error or some other specific event occurs
      const onError = event => {
        if (event) innerAlert(event.data)
      }

      // the document is opened for editing with the old document.key value
      const onOutdatedVersion = event => {
        this.$refs.editor.reload(true)
        console.log(event)
      }

      // replace the link to the document which contains a bookmark
      const replaceActionLink = (href, linkParam) => {
        let link
        const actionIndex = href.indexOf('&actionLink=')
        if (actionIndex !== -1) {
          const endIndex = href.indexOf('&', actionIndex + '&actionLink='.length)
          if (endIndex !== -1) {
            link = `${href.substring(0, actionIndex) + href.substring(endIndex)}&actionLink=${encodeURIComponent(
              linkParam
            )}`
          } else {
            link = `${href.substring(0, actionIndex)}&actionLink=${encodeURIComponent(linkParam)}`
          }
        } else {
          link = `${href}&actionLink=${encodeURIComponent(linkParam)}`
        }
        return link
      }

      // the user is trying to get link for opening the document which contains a bookmark, scrolling to the bookmark position
      const onMakeActionLink = event => {
        const actionData = event.data
        const linkParam = JSON.stringify(actionData)
        docEditor.setActionLink(replaceActionLink(this.$refs.editor.src, linkParam))
      }

      // the meta information of the document is changed via the meta command
      const onMetaChange = event => {
        if (event.data.favorite) {
          const favorite = !!event.data.favorite
          docEditor.setFavorite(favorite)
        }
        innerAlert(`onMetaChange: ${JSON.stringify(event.data)}`)
      }

      // var dataInsertImage = [[${dataInsertImage}]];
      const dataInsertImage = {}

      // the user is trying to insert an image by clicking the Image from Storage button
      const onRequestInsertImage = event => {
        const temp = Object.assign({}, { c: event.data.c }, dataInsertImage)
        docEditor.insertImage(temp)
      }

      // the user is trying to select document for comparing by clicking the Document from Storage button
      const onRequestCompareFile = () => {
        // docEditor.setRevisedFile([[${dataCompareFile}]]);
        docEditor.setRevisedFile({})
      }

      // the user is trying to select recipients data by clicking the Mail merge button
      const onRequestMailMergeRecipients = event => {
        // docEditor.setMailMergeRecipients([[${dataMailMergeRecipients}]]);
        console.log(event)
        docEditor.setMailMergeRecipients({})
      }

      if (config.editorConfig.user.name === 'Anonymous') {
        config.editorConfig.user.name = ''
      }

      const onRequestSaveAs = event => {
        //  the user is trying to save file by clicking Save Copy as... button
        const title = event.data.title
        const url = event.data.url
        const data = {
          title,
          url
        }
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'saveas')
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify(data))
        xhr.onload = () => {
          innerAlert(xhr.responseText)
          innerAlert(JSON.parse(xhr.responseText).file, true)
        }
      }

      const onRequestRename = event => {
        //  the user is trying to rename file by clicking Rename... button
        innerAlert(`onRequestRename: ${JSON.stringify(event.data)}`)
        console.log(event)

        const newfilename = event.data
        const data = {
          newfilename,
          dockey: config.document.key,
          ext: config.document.fileType
        }
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'rename')
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify(data))
        xhr.onload = () => {
          innerAlert(xhr.responseText)
        }
      }

      const onRequestReferenceData = event => {
        // user refresh external data source
        event.data.directUrl = !!config.document.directUrl
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'reference')
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(JSON.stringify(event.data))
        xhr.onload = () => {
          innerAlert(xhr.responseText)
          docEditor.setReferenceData(JSON.parse(xhr.responseText))
        }
      }

      config.width = '100%'
      config.height = '100%'
      config.events = {
        onAppReady,
        onDocumentStateChange,
        onError,
        onOutdatedVersion,
        onMakeActionLink,
        onMetaChange,
        onRequestInsertImage,
        onRequestCompareFile,
        onRequestMailMergeRecipients
      }

      // var histArray = [[${fileHistory}]];
      const histArray = []
      const hist = histArray[0]
      const historyData = histArray[1]
      // var usersForMentions = [[${usersForMentions}]];
      const usersForMentions = []

      if (config.editorConfig.user.id !== 4) {
        if (hist && historyData) {
          // the user is trying to show the document version history
          config.events.onRequestHistory = () => {
            docEditor.refreshHistory(JSON.parse(hist)) // show the document version history
          }
          // the user is trying to click the specific document version in the document version history
          config.events.onRequestHistoryData = event => {
            const ver = event.data
            const histData = historyData
            docEditor.setHistoryData(JSON.parse(histData)[ver - 1]) // send the link to the document for viewing the version history
          }
          // the user is trying to go back to the document from viewing the document version history
          config.events.onRequestHistoryClose = () => {
            this.$refs.editor.reload()
          }
        }
        // add mentions for not anonymous users
        config.events.onRequestUsers = () => {
          docEditor.setUsers({
            // set a list of users to mention in the comments
            users: usersForMentions
          })
        }
        // the user is mentioned in a comment
        config.events.onRequestSendNotify = event => {
          event.data.actionLink = replaceActionLink(this.$refs.editor.src, JSON.stringify(event.data.actionLink))
          const data = JSON.stringify(event.data)
          innerAlert(`onRequestSendNotify: ${data}`)
        }
        // prevent file renaming for anonymous users
        config.events.onRequestRename = onRequestRename
        config.events.onRequestReferenceData = onRequestReferenceData
        // prevent switch the document from the viewing into the editing mode for anonymous users
        config.events.onRequestEditRights = onRequestEditRights
      }

      if (config.editorConfig.createUrl) {
        config.events.onRequestSaveAs = onRequestSaveAs
      }

      docEditor = new DocsAPI.DocEditor(this.editorId, config)
      this.docEditor = docEditor
    },
    beforeDestroy() {
      this.docEditor?.destroyEditor()
    }
  }
</script>

<style lang="scss">
  .editor {
    width: 100%;
    height: 100%;
  }
</style>
